package com.cn.jinl.service;

import com.cn.jinl.api.IDeviceService;
import com.cn.jinl.api.ISterilizeService;
import com.cn.jinl.conf.Config;
import com.cn.jinl.dao.CheckLineMapper;
import com.cn.jinl.dao.ChenxingMachineMapper;
import com.cn.jinl.dao.OnDutyProductMapper;
import com.cn.jinl.dao.SterilizeMapper;
import com.cn.jinl.domain.*;
import com.cn.jinl.utils.CommonUtil;
import com.cn.jinl.utils.Constants;
import com.cn.jinl.utils.QueryForm;
import com.cn.jinl.utils.WordUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class SterilizeServiceImpl implements ISterilizeService {

    @Autowired
    private SterilizeMapper sterilizeMapper;

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private ChenxingMachineMapper chenxingMachineMapper;

    @Autowired
    private OnDutyProductMapper onDutyProductMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private Config config;

    @Override
    public List<Sterilize> getSterilizeList(QueryForm queryForm) throws Exception {
        String tabName = queryForm.getTabName();
        if(StringUtils.isEmpty(tabName)){
            return Lists.newArrayList();
        }
        if(StringUtils.equals(tabName,"U管成型")){
            tabName = "成型";
        }
        Map<String,List<String>> deviceMaps = deviceService.getDeviceByProcName(tabName,"");
        List<Sterilize> sterilizes = sterilizeMapper.selectLatestSterilizes(queryForm);
        Map<String,Sterilize> sterilizeMap = Maps.newHashMap();
        for(Sterilize sterilize :sterilizes ){
            sterilizeMap.put(sterilize.getDeviceCode(),sterilize);
        }

        List<Sterilize> results = Lists.newLinkedList();
        for(String key :deviceMaps.keySet() ){
            List<String> deviceCodes = deviceMaps.get(key);
            for(String code : deviceCodes){
                if(sterilizeMap.containsKey(code)){
                    results.add(sterilizeMap.get(code));
                }else{
                    Sterilize add = new Sterilize();
                    add.setDeviceCode(code);
                    add.setSterilizeStatus("0");
                    results.add(add);
                }
            }

        }
        Collections.sort(results, new Comparator<Sterilize>() {
            @Override
            public int compare(Sterilize o1, Sterilize o2) {
                if(o1.getDeviceCode().compareTo(o2.getDeviceCode()) < 0){
                    return -1;
                }
                return 1;
            }
        });
        return results;
    }

    @Override
    public List<Sterilize> getSterilizeHistoryList(QueryForm queryForm) throws Exception {
        int count = sterilizeMapper.selectLatestHistorySterilizesCount(queryForm);
        if(count == 0){
            return Lists.newArrayList();
        }
        List<Sterilize> sterilizes = sterilizeMapper.selectLatestHistorySterilizes(queryForm);
        sterilizes.get(0).setCount(count);
        return sterilizes;
    }

    @Override
    public String addSterilize(Sterilize sterilize) throws Exception {
        String id = CommonUtil.generateRandomNum("sterilize-");
        sterilize.setId(id);
        int count = sterilizeMapper.insertSelective(sterilize);
        return CommonUtil.outStr(count);
    }


    @Override
    public String updateSterilize(Sterilize sterilize) throws Exception {
        String id = sterilize.getId();
        if(StringUtils.isEmpty(id)){
            return "缺少主键！";
        }

        SterilizeExample example = new SterilizeExample();
        example.createCriteria().andIdEqualTo(id);
        int count = sterilizeMapper.updateByExampleSelective(sterilize,example);
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateCloseSterilize(String id) throws Exception {
        if(StringUtils.isEmpty(id)){
            return "缺少主键！";
        }
        Sterilize sterilize = new Sterilize();
        sterilize.setSterilizeStatus("0");
        SterilizeExample example = new SterilizeExample();
        example.createCriteria().andIdEqualTo(id);
        int count = sterilizeMapper.updateByExampleSelective(sterilize,example);
        return CommonUtil.outStr(count);
    }

    @Override
    public String exportSterilizeHistoryList(QueryForm queryForm) throws Exception {
        List<Sterilize> sterilizes = sterilizeMapper.selectLatestAllHistorySterilizes(queryForm);
        String path = request.getSession().getServletContext().getRealPath("/WEB-INF/classes/");
        Map<String,Object> maps = Maps.newHashMap();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String queryTime = simpleDateFormat.format(new Date());
        maps.put("queryTime",queryTime);
        maps.put("userName",queryForm.getName());
        String period = queryForm.getStartTime()+"至"+queryForm.getEndTime().split(" ")[0];
        maps.put("queryPeriod",period);
        maps.put("queryCount",sterilizes.size());
        Map<String,String>deviceMaps = deviceService.getDeviceCodeItemName();
        for(int i =0 ;i < sterilizes.size(); i++){
            Sterilize sterilize = sterilizes.get(i);
            if(StringUtils.isEmpty(sterilize.getDeviceCode())){
                sterilize.setDeviceCode("");
            }
            sterilize.setIndex(i+1);
            sterilize.setProcessName(deviceMaps.get(sterilize.getDeviceCode()));
            if(StringUtils.isEmpty(sterilize.getProcessName())){
                sterilize.setProcessName("");
            }
        }
        maps.put("sterilizes",sterilizes);
        String fileName = WordUtil.generateSterilizePdfPath(path,config.filePath,"xiaodu.ftl",maps);
        return config.fileUrl+fileName;
    }

//    @Scheduled(cron = "0 0 */1 * * ?")
//    public void updateSterilizeEveryDay(){
//        QueryForm queryForm = new QueryForm();
//        queryForm.setTabName("U管成型");
//        List<Sterilize> sterilizes = sterilizeMapper.selectLatestSterilizes(queryForm);
//        if(CollectionUtils.isEmpty(sterilizes)){
//            return;
//        }
//        List<Sterilize> inserts = Lists.newArrayList();
//        for(Sterilize sterilize :sterilizes){
//            Sterilize add = new Sterilize();
//            add.setId(CommonUtil.generateRandomNum("sterilize-"));
//            add.setSterilizeUserName(sterilize.getSterilizeUserName());
//            add.setSterilizeType(sterilize.getSterilizeType());
//            add.setTabName(sterilize.getTabName());
//            add.setDeviceCode(sterilize.getDeviceCode());
//            add.setSterilizeWater(sterilize.getSterilizeWater());
//            add.setSterilizeStatus(sterilize.getSterilizeStatus());
//            inserts.add(add);
//        }
//        sterilizeMapper.batchInsertSterilizes(inserts);
//
//    }

    @Scheduled(cron = "0 0/10 * * * ?")
    public void updateSterilizeEveryDay(){
        Map<String,String>dutyMap = CommonUtil.getOnDutyAndWhiteDay();
        String dutyDay = dutyMap.get("dutyDay");
        String whiteDay = dutyMap.get("whiteDay");
        ChenxingMachineExample example = new ChenxingMachineExample();
        example.createCriteria().andWhiteDayEqualTo(whiteDay).andDutyDayEqualTo(dutyDay).andStatusEqualTo(Constants.NORMAL_STATUS).andQjStatusEqualTo("1");
        List<ChenxingMachine>chenxingMachines = chenxingMachineMapper.selectByExample(example);
        QueryForm queryForm = new QueryForm();
        queryForm.setTabName("U管成型");
        List<Sterilize> sterilizes = sterilizeMapper.selectLatestSterilizes(queryForm);
        Map<String,Long> sterMap = Maps.newHashMap();
        for(Sterilize sterilize :sterilizes){
            sterMap.put(sterilize.getDeviceCode(),sterilize.getCreateTime().getTime());
        }
        List<Sterilize> inserts = Lists.newArrayList();
        Date now = new Date();
        for(ChenxingMachine chenxingMachine :chenxingMachines){
            long chenxingTime = chenxingMachine.getCreateTime().getTime();
            if(sterMap.containsKey(chenxingMachine.getDeviceCode())){
                long timeStamp = sterMap.get(chenxingMachine.getDeviceCode());
                if(Math.abs(timeStamp - now.getTime() )< 3600L*1000L){
                    continue;
                }
            }else {
                if(Math.abs(now.getTime() - chenxingTime )< 3600L*1000L){
                    continue;
                }
            }
            Sterilize add = new Sterilize();
            add.setId(CommonUtil.generateRandomNum("sterilize-"));
            add.setSterilizeUserName(chenxingMachine.getQjUserName());
            add.setSterilizeType("1");
            add.setTabName("U管成型");
            add.setDeviceCode(chenxingMachine.getDeviceCode());
            add.setSterilizeWater("75%酒精");
            add.setSterilizeStatus("1");
            inserts.add(add);
        }
        queryForm.setTabName("包装");
        sterilizes = sterilizeMapper.selectLatestSterilizes(queryForm);
        Map<String,Long> baoMap = Maps.newHashMap();
        for(Sterilize sterilize :sterilizes){
            baoMap.put(sterilize.getDeviceCode(),sterilize.getCreateTime().getTime());
        }
        OnDutyProductExample onDutyProductExample = new OnDutyProductExample();
        onDutyProductExample.createCriteria().andWhiteDayEqualTo(whiteDay).andDutyDayEqualTo(dutyDay).andStatusEqualTo(Constants.NORMAL_STATUS).andProductStatusEqualTo("2");
        List<OnDutyProduct> onDutyProducts = onDutyProductMapper.selectByExample(onDutyProductExample);
        for(OnDutyProduct onDutyProduct :onDutyProducts){
            long chenxingTime = onDutyProduct.getCreateTime().getTime();
            if(baoMap.containsKey(onDutyProduct.getDeviceCode())){
                long timeStamp = baoMap.get(onDutyProduct.getDeviceCode());
                if(Math.abs(timeStamp - now.getTime() )< 3600L*1000L){
                    continue;
                }
            }else {
                if(Math.abs(now.getTime() - chenxingTime )< 2*1000L){
                    continue;
                }
            }
            Sterilize add = new Sterilize();
            add.setId(CommonUtil.generateRandomNum("sterilize-"));
            String operateName = onDutyProduct.getOperateUserName();
            if(StringUtils.isNotEmpty(operateName)){
                operateName = operateName.split(",")[0];
            }
            add.setSterilizeUserName(operateName);
            add.setSterilizeType("1");
            add.setTabName("包装");
            add.setDeviceCode(onDutyProduct.getDeviceCode());
            add.setSterilizeWater("75%酒精");
            add.setSterilizeStatus("1");
            inserts.add(add);
        }
        if(CollectionUtils.isEmpty(inserts)){
            return;
        }
        sterilizeMapper.batchInsertSterilizes(inserts);

    }
}
